package com.cy.system.aspect;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cy.system.annotation.SysLog;
import com.cy.system.config.DataSourceContextHolder;
import com.cy.system.config.UserSession;
import com.cy.system.entity.SystemLog;
import com.cy.system.entity.User;
import com.cy.system.mapper.SysLogMapper;

@Aspect
@Component
public class SysAspect {
	private final static Logger logger = Logger.getLogger(SysAspect.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Resource
	SysLogMapper sysLogMapper;
	
	@Around("within(com.cy..*) && @annotation(sysLog)")
	public Object doAroundMethod(ProceedingJoinPoint pjd,SysLog sysLog) {	
		SystemLog systemLog = new SystemLog();
		Date startDate = new Date();
		systemLog.setStartTime(startDate);
		
		Object result = "";
		//###################上面代码为方法执行前#####################
        try {
			result  = pjd.proceed();
			
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//执行方法，获取返回参数
        //###################下面代码为方法执行后#####################
        /*HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
        HttpSession session =request.getSession();*/ 
        UserSession userSession = new UserSession();
        HttpSession session = userSession.getUserSession();
        if(null!=session) {
        	User user = (User)session.getAttribute("userSession");
            if(null != user) {
            	logger.info("==> 获取userSession！");
            	systemLog.setOperUser(user.getUserName());
            }else {
            	 systemLog.setOperUser("user为空");
            }
        }
        systemLog.setOperType(sysLog.operType());
        Object[] inParams = pjd.getArgs();
        StringBuffer inParamsStr= new StringBuffer();
        for(Object param : inParams) {
        	inParamsStr.append(param.toString());
        }
        if(inParamsStr.toString().length()>100) {
        	systemLog.setInParams(inParamsStr.toString().substring(0, 100));
        }else {
        	systemLog.setInParams(inParamsStr.toString());
        }
        if(result.toString().length()>100) {
        	systemLog.setOutResult(result.toString().substring(0, 100));
        }else {
        	systemLog.setOutResult(result.toString());
        }
        
        Date endDate = new Date();
        double runTime = (double) ((endDate.getTime()-startDate.getTime())/10)/100;  //先转为double,再除才能保证精度
        /*DecimalFormat dFormat = new DecimalFormat("#.00");
        String runTime = (double)dFormat.format(runTime); */   
        /*System.out.println(runTime);*/
        systemLog.setRunTime(runTime); 
        logger.info("==> 记录服务调用--------------------------------------------");
        logger.info("==> 服务类型["+systemLog.getOperType()+"]");
        logger.info("==> 服务调用用户["+systemLog.getOperUser()+"]");
        logger.info("==> 服务调用startTime["+sdf.format(startDate)+"]");
        logger.info("==> 服务调用endTime["+sdf.format(endDate)+"]");
        logger.info("==> 服务执行runTime["+systemLog.getRunTime()+"]<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        if(sysLog.isWrite()) {
        	DataSourceContextHolder.setDbType("sysLogDataSource");
            sysLogMapper.writeSysLog(systemLog);
            DataSourceContextHolder.clearDbType();
        };
        return result;
	}
}
